/**
 * 
 */
package com.base.myproject.client.busi.b2c.manager;

import java.util.ArrayList;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.JDBCModelData;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.SystemMessage;
import com.base.myproject.client.tools.SendServlet;
import com.base.myproject.client.ui.BaseAdvSearch;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.RowNumberer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FlowData;
import com.extjs.gxt.ui.client.widget.layout.FlowLayout;
import com.extjs.gxt.ui.client.widget.menu.Item;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author zgw 2009-8-19 下午02:29:54 javazgw@gmail.com
 */
@SuppressWarnings("unchecked")
public class B2cSuit extends BaseJDBCPanel implements
		com.extjs.gxt.ui.client.event.Listener<ButtonEvent> {

	final static String busi = "9005";
	BaseStore<JDBCModelData> store = null;

	BaseGrid grid = null;
	BaseStore<JDBCModelData> suitstore;
	BaseGrid suitgrid = null;
	BaseGrid dialoggrid = null;
	TextField<String> sultname;

	public B2cSuit() {
		super();
		init();
	}

	public void init() {
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 5, 0, 0));
		this.add(initWeiget(), centerData);
		this.setWidth(960);
		this.setHeight(1000);
		// super.init();

		registerMainStore(getStore());
		registerStore(getStore());

		this.setBusino(busi);

		// setdefault();
	}

	public ContentPanel initWeiget() {
		ContentPanel panel = new ContentPanel();
		panel.add(CreateB2cGcode());
		panel.add(CreateB2cGcodeSuit());
		panel.setHeaderVisible(false);
		return panel;
	}

	private void CreateStore() {

	}

	private ContentPanel CreateB2cGcode() {
		ContentPanel panel = new ContentPanel();
		ToolBar tb = new ToolBar();
		Button addsuit = new Button("从商品库里添加套装商品");
		addsuit.setIconStyle("b2csuit");
		panel.setHeading("商品库，如果加入套装你必须先选择一行（必选）");
		tb.add(addsuit);
		panel.setTopComponent(tb);
		addsuit.addListener(Events.Select, this);
		panel.setAutoWidth(true);
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		ColumnConfig gcode = new ColumnConfig("gcode", "商品大类编码", 100);
		TextField<String> gcodetext = new TextField<String>();
		gcode.setEditor(new CellEditor(gcodetext));
		columns.add(gcode);
		ColumnConfig gname = new ColumnConfig("gname", "商品大类名称", 100);
		TextField<String> gnametext = new TextField<String>();
		gname.setEditor(new CellEditor(gnametext));
		columns.add(gname);

		ColumnConfig treecode = new ColumnConfig("treecode", "商品分类树编码", 100);

		TextField<String> treecodetext = new TextField<String>();
		treecode.setEditor(new CellEditor(treecodetext));
		columns.add(treecode);

		ColumnConfig b2cgcodecolumn = new ColumnConfig("b2cgcode", "商品编码", 100);
		TextField<String> b2cgcodetext = new TextField<String>();
		b2cgcodecolumn.setEditor(new CellEditor(b2cgcodetext));
		columns.add(b2cgcodecolumn);
		ColumnConfig b2cgname = new ColumnConfig("b2cgname", "商品名称", 100);
		TextField<String> b2cgnametext = new TextField<String>();
		b2cgname.setEditor(new CellEditor(b2cgnametext));
		columns.add(b2cgname);

		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("gcode");
		type.addField("gname");
		type.addField("b2cgcode");
		type.addField("b2cgname");
		type.addField("mainimagepath");
		type.addField("treecode");
		type.addField("detailimage");

		StoreInfo info = new StoreInfo();

		info.setTablename("b2cgcode");
		info.setKeyname(new String[] { "b2cgcode" });
		info.setSql("select * from b2cgcode");
		// info.setParent(store);// 关联主表
		// info.setAutoinccolumn("idx"); // 自增字段，如果子表一定需要
		// info.setLinkparentcolumns(new String[] { "ccode" }); // 关联主表字段
		store = new BaseStore<JDBCModelData>(type, info);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid(store, cm);

		cbs.setSelectionMode(SelectionMode.SINGLE);

		grid.setSelectionModel(cbs);
		grid.setAutoHeight(true);
		grid.setAutoWidth(true);

		registerStore(store);
		panel.add(grid);
		// panel.add(aa());
		return panel;
	}

	/**
	 * 套装商品
	 * 
	 * @return
	 */
	private ContentPanel CreateB2cGcodeSuit() {
		ContentPanel panel = new ContentPanel();

		panel.setAutoWidth(true);
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig b2cgcodelinkcolumn = new ColumnConfig("b2cgcodelink",
				"商品编码", 100);

		columns.add(b2cgcodelinkcolumn);
		ColumnConfig b2cgname = new ColumnConfig("b2cgname", "商品名称", 100);

		columns.add(b2cgname);
		ColumnConfig suitname = new ColumnConfig("suitname", "套装商品名称", 100);

		columns.add(suitname);

		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");

		type.addField("b2cgcode");
		type.addField("icode");
		type.addField("b2cgcodelink");
		type.addField("b2cgname");
		type.addField("suitname");

		StoreInfo info = new StoreInfo();

		info.setTablename("b2csuit");
		// info.setKeyname(new String[]{"b2cgcode"});
		info
				.setSql("select icode,b2cgcode,b2cgcodelink,(select b2cgname from b2cgcode where b2cgcode.b2cgcode = b2csuit.b2cgcodelink )as b2cgname,suitname from b2csuit");
		info.setParent(store);// 关联主表
		// info.setAutoinccolumn("idx"); // 自增字段，如果子表一定需要
		info.setLinkparentcolumns(new String[] { "b2cgcode" }); // 关联主表字段
		suitstore = new BaseStore<JDBCModelData>(type, info);
		// setSuitstore(new BaseStore<JDBCModelData>(type, info));
		ColumnModel cm = new ColumnModel(columns);
		suitgrid = new BaseGrid(getSuitstore(), cm, true, false) {
			public void ContentMenu() {
				Menu m = new Menu();

				Item deleteitem = new MenuItem("删除行选中行",
						new SelectionListener<MenuEvent>() {

							@Override
							public void componentSelected(MenuEvent ce) {
								String icode =((BaseModelData)suitgrid.getSelectionModel().getSelectedItems().get(0)).get("icode");
								System.out.println("icode="+icode);
								deletesuitgcode(icode);
								deleterecord();
								
							}

						});

				m.add(deleteitem);
				this.setContextMenu(m);
			}
		};

		cbs.setSelectionMode(SelectionMode.SINGLE);

		suitgrid.setSelectionModel(cbs);
		suitgrid.setAutoHeight(true);
		suitgrid.setAutoWidth(true);

		// registerStore(store); //不关联，取消系统的统一保存
		panel.add(suitgrid);
		return panel;
	}

	ContentPanel dialoggcode() {

		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		ColumnConfig gcode = new ColumnConfig("gcode", "商品大类编码", 100);
		TextField<String> gcodetext = new TextField<String>();
		gcode.setEditor(new CellEditor(gcodetext));
		columns.add(gcode);
		ColumnConfig gname = new ColumnConfig("gname", "商品大类名称", 100);
		TextField<String> gnametext = new TextField<String>();
		gname.setEditor(new CellEditor(gnametext));
		columns.add(gname);

		ColumnConfig treecode = new ColumnConfig("treecode", "商品分类树编码", 100);

		TextField<String> treecodetext = new TextField<String>();
		treecode.setEditor(new CellEditor(treecodetext));
		columns.add(treecode);

		ColumnConfig b2cgcodecolumn = new ColumnConfig("b2cgcode", "商品编码", 100);
		TextField<String> b2cgcodetext = new TextField<String>();
		b2cgcodecolumn.setEditor(new CellEditor(b2cgcodetext));
		columns.add(b2cgcodecolumn);
		ColumnConfig b2cgname = new ColumnConfig("b2cgname", "商品名称", 100);
		TextField<String> b2cgnametext = new TextField<String>();
		b2cgname.setEditor(new CellEditor(b2cgnametext));
		columns.add(b2cgname);
		DateField dateField = new DateField();

		final ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("gcode");
		type.addField("gname");
		type.addField("b2cgcode");
		type.addField("b2cgname");
		type.addField("mainimagepath");
		type.addField("treecode");
		type.addField("detailimage");

		// type.addField("Phone");
		// type.addField("imagepath");
		StoreInfo info = new StoreInfo();
		info.setTablename("b2cgcode");
		// info.setKeyname(new String[]{"b2cgcode"});
		info.setSql("select * from b2cgcode");
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();

		RowNumberer r = new RowNumberer(); // 显示行号
		columns.add(0, r);
		columns.add(1, cbs.getColumn()); // 默认的选择方式，如果不加入就有bug，在外层不需要加入
		ColumnModel cm = new ColumnModel(columns);
		BaseStore b2cstore = new BaseStore();

		b2cstore.setType(type);
		b2cstore.setStoreinfo(info);
		PagingToolBar toolBar = new PagingToolBar(50);
		// toolBar.bind( (BasePagingLoader)store.getLoader());
		b2cstore.setToolBar(toolBar);
		b2cstore.initcompleted();
		// toolBar.bind((BasePagingLoader)store.getLoader());
		dialoggrid = new BaseGrid(b2cstore, cm);

		// grid.setSelectionModel(cbs);
		dialoggrid.setLoadMask(true);

		cbs.setSelectionMode(SelectionMode.MULTI);
		dialoggrid.setSelectionModel(cbs);

		BaseAdvSearch ba = new BaseAdvSearch();
		ba.bindBaseStore(b2cstore);

		ContentPanel panel = new ContentPanel();
		panel.setFrame(true);

		panel.setButtonAlign(HorizontalAlignment.CENTER);
		panel.setIconStyle("icon-table");
		panel.setHeading("");
		panel.setLayout(new FlowLayout());

		panel.setSize(600, 350);
		// grid.setSize(600, 350);
		dialoggrid.setAutoHeight(true);
		dialoggrid.setAutoWidth(true);
		// grid.setHeight("100%");
		// grid.setWidth("100%");
		// DomHelper.insertHtml("beforeEnd", grid.el().dom, "sssssss");

		// grid.setWidth("100%");
		// grid.setHeight("100%");
		panel.setScrollMode(Scroll.AUTO);
		panel.add(ba.getAdvsearch(), new FlowData(1));
		panel.add(dialoggrid, new FlowData(1));
		panel.setHeight("100%");
		panel.setWidth("100%");
		panel.setBottomComponent(toolBar);

		StoreFilterField<ModelData> field = new StoreFilterField<ModelData>() {
			@Override
			protected boolean doSelect(Store<ModelData> store,
					ModelData parent, ModelData record, String property,
					String filter) {

				for (int i = 0; i < type.getFieldCount(); i++) {

					String name = (String) record.get(type.getField(i)
							.getName());

					// TODO
					if (name != null
							&& name.indexOf(filter.toLowerCase()) != -1) {
						return true;
					}
				}
				return false;
			}

			@Override
			protected void onFilter() {
				super.onFilter();

				// grid.getSelectionModel().select(0);
			}

		};
		field.setWidth("100%");
		field.setToolTip("对当前页面进行查找");
		field.bind(b2cstore);
		field.setFieldLabel("当页搜索");
		panel.setTopComponent(field);
		panel.setAutoHeight(true);
		panel.setHeading("请选择组成套装的商品（可多选）（必选）");
		return panel;
	}

	/**
	 * @return the store
	 */
	public BaseStore<JDBCModelData> getStore() {
		return store;
	}

	/**
	 * @param store
	 *            the store to set
	 */
	public void setStore(BaseStore<JDBCModelData> store) {
		this.store = store;
	}

	/**
	 * @return the grid
	 */
	public BaseGrid getGrid() {
		return grid;
	}

	/**
	 * @param grid
	 *            the grid to set
	 */
	public void setGrid(BaseGrid grid) {
		this.grid = grid;
	}

	/**
	 * @return the suitstore
	 */
	public BaseStore<JDBCModelData> getSuitstore() {
		return suitstore;
	}

	/**
	 * @param suitstore
	 *            the suitstore to set
	 */
	public void setSuitstore(BaseStore<JDBCModelData> suitstore) {
		this.suitstore = suitstore;
	}

	/**
	 * @return the suitgrid
	 */
	public BaseGrid getSuitgrid() {
		return suitgrid;
	}

	/**
	 * @param suitgrid
	 *            the suitgrid to set
	 */
	public void setSuitgrid(BaseGrid suitgrid) {
		this.suitgrid = suitgrid;
	}

	@Override
	public void handleEvent(ButtonEvent be) {
		System.out.println(be.getButton().getId());
		if (be.getButton().getText().equals("从商品库里添加套装商品")) {
			if (getGrid().getSelectionModel().getSelectedItems().size() <= 0) {
				MessageBox.alert("警告", "你必须先选择一条对应的商品。", null);
				return;

			}

			Dialog d = new Dialog();
			d.setWidth(600);
			d.setAutoHeight(true);
			d.add(CreateSuitname());
			d.add(dialoggcode());

			d.getButtonById(Dialog.OK).addListener(Events.Select, this);
			// d.setHideOnButtonClick(true);
			d.show();
		}
		// TODO 此处可能有bug，名字在国际化的时候会变
		else if (be.getButton().getText().equals("确定")) {

			System.out.println(be.getButton().getText());
			System.out.println(getDialoggrid().getSelectionModel()
					.getSelectedItems().size());
			String str = "";
			System.out.println(sultname.getValue());
			for (int i = 0; i < getDialoggrid().getSelectionModel()
					.getSelectedItems().size(); i++) {
				System.out.println(getDialoggrid().getSelectionModel()
						.getSelectedItems().get(i).getClass());
				((BaseModelData) getDialoggrid().getSelectionModel()
						.getSelectedItems().get(i)).get("b2cgcode");
				str += ""
						+ ((BaseModelData) getDialoggrid().getSelectionModel()
								.getSelectedItems().get(i)).get("b2cgcode")
						+ ",";

			}
			if (str.equals("")
					|| sultname.getValue() == null
					|| sultname.getValue().trim().equals("")
					|| getGrid().getSelectionModel().getSelectedItems().size() <= 0) {
				MessageBox.alert("警告", "你有必录（必选）项没有操作。", null);
			}
			else
			{

			copy2server(str);
			}
		}
	}

	Widget CreateSuitname() {
		HorizontalPanel hpanel = new HorizontalPanel();
		Label l = new Label("套装名称(必录)：");
		sultname = new TextField<String>();

		hpanel.add(l);
		hpanel.add(sultname);
		return hpanel;
	}

	void copy2server(String str) {
		String b2cgcode = ((BaseModelData) getGrid().getSelectionModel()
				.getSelectedItems().get(0)).get("b2cgcode");

		SendServlet ss = new SendServlet();
		String respose = ss.getStringx("/"+GWT.getModuleName()+"/BaseServlet", "Action="
				+ SystemMessage.getMessage(2, 3) + "&b2cgcodestr=" + str
				+ "&b2cgcode=" + b2cgcode+"&suitname="+sultname.getValue());
		System.out.println(respose);
		getSuitstore().reload();
	}
	void deletesuitgcode(String icode)
	{
		SendServlet ss = new SendServlet();
		String respose = ss.getStringx("/"+GWT.getModuleName()+"/BaseServlet", "Action="
				+ SystemMessage.getMessage(2, 4) + "&icode=" + icode);
		System.out.println(respose);
		if(respose.equals(SystemMessage.getMessage(1, 0)))
		{
			Info.display("提示", "删除成功");
		}
		else
		{
			Info.display("警告", "删除失败，请刷新后再次删除。（与服务器通信失败）");
		}
		
	}

	/**
	 * @return the dialoggrid
	 */
	public BaseGrid getDialoggrid() {
		return dialoggrid;
	}

	/**
	 * @param dialoggrid
	 *            the dialoggrid to set
	 */
	public void setDialoggrid(BaseGrid dialoggrid) {
		this.dialoggrid = dialoggrid;
	}

}
